import { onMounted, onUnmounted } from "vue"

export const useLog = function () {

    let time = Date.now();

    function onShow() {
        if (document.visibilityState === "visible") {
            // 页面从隐藏状态切换到可见状态时执行的代码
            console.log("页面已显示", location.href);
            time = Date.now();
        } else if (document.visibilityState === "hidden") {
            // 页面从可见状态切换到隐藏状态时执行的代码
            console.log("页面已隐藏", location.href);
            let t = Date.now() - time;
            console.log("timer", location.href, t);
            localStorage.setItem(location.href, Math.floor(t / 1000) + "")
        }
    }

    function onState(e:any){
        console.log("路由变化", e, location.href);
    }

    onMounted(() => {
        document.addEventListener("visibilitychange", onShow);
        window.addEventListener("beforeunload", function(event) {
            localStorage.setItem("beforeunload", (new Date()).toUTCString())
        });
    })

    onUnmounted(() => {
        document.removeEventListener("visibilitychange", onShow);
    })

    console.log("start log");
}